from datetime import datetime, timedelta

import pytz
from celery import shared_task
from django.db.models import Q
from django.utils import timezone

from paper.models import TestRecord
import ebisu
from celery.utils.log import get_task_logger

logger = get_task_logger(__name__)


@shared_task()
def hi():
    print('你好，世界!')
    return '你好，世界!'


@shared_task
def cal():
    now = timezone.now()
    now_before3 = now + timedelta(hours=-1)
    qs = TestRecord.objects.filter(Q(last_cal__lte=now_before3) | Q(last_cal__isnull=True))
    print('记录数:%d' % qs.count())
    recalls = []
    if qs.count() > 0:
        print('计算...')
        one = timedelta(hours=1)
        for q in qs:
            model = (q.alpha, q.beta, q.t)
            recall = ebisu.predictRecall(model, (now - q.last_test) / one, exact=True)
            q.recall = round(recall * 100)
            q.last_cal = timezone.now()
            q.save()
            recalls.append(recall)
        return 'recall: %s' % ','.join([str(r) for r in recalls])
    return 'recall not cal'
